//
//  ClassesVC.m
//  GIFShow
//
//  Created by lanou11air029 on 15/4/9.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "ClassesVC.h"
#import "MYTableViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "ClassLabelModel.h"
#import "MySettingOptions.h"
#import "TMQuiltView.h"
#import "TMQuiltViewCell.h"
#import "TMPhotoQuiltViewCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "GifController.h"
#import "NSString+UrlEncode.h"
#import "ClassSettingView.h"
#import <MBProgressHUD/MBProgressHUD.h>
@interface ClassesVC ()<myTableViewScrollDelegate,TMQuiltViewDataSource,TMQuiltViewDelegate>
{
    TMQuiltView *qtmquitView;
    ClassSettingView * classView;
}

//@property (strong, nonatomic)MYTableViewController * firstTableVC;
//@property (strong, nonatomic)MYTableViewController * secondTableVC;
@property (strong, nonatomic) NSMutableArray * totalArray;
@property (strong, nonatomic) NSMutableArray * likeArray;
@property (strong, nonatomic) NSMutableArray * sourceArray;
@property (strong, nonatomic) UIActivityIndicatorView * classIndeicatorView;
@property (strong, nonatomic) NSMutableArray * allClassModelArray;
@end

@implementation ClassesVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    NSString * backColor = [MySettingOptions defaultOptions].backColor;
    if(self.view.frame.size.width == 375){
        NSString * back = [NSString stringWithFormat:@"%@6",backColor];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:back]];
    }else{
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:backColor]];
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self getDataWithUrlStr:self.urlStr];
    [self.classIndeicatorView startAnimating];
    qtmquitView = [[TMQuiltView alloc] initWithFrame:CGRectMake(0, 1, self.view.bounds.size.width, self.view.bounds.size.height - 114)];
    qtmquitView.delegate = self;
    qtmquitView.dataSource = self;
    
    [self.view addSubview:qtmquitView];
    
    [qtmquitView reloadData];
//    UIBarButtonItem * setBarBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_setting"] style:UIBarButtonItemStylePlain target:self action:@selector(didClickSettingBarButton:)];
    UIBarButtonItem * fenleiBarBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_fenlei"] style:UIBarButtonItemStylePlain target:self action:@selector(didClickFenleiBarButton:)];
//    self.navigationItem.rightBarButtonItems = @[setBarBtn,fenleiBarBtn];
    self.navigationItem.rightBarButtonItem = fenleiBarBtn;
    [self myTheme];
    [[NSNotificationCenter defaultCenter]addObserverForName:@"ChangeTheme" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [self myTheme];
    }];

//    http://gif.duowan.com/index.php?r=gif/labelList&page=1&pageSize=30
    // Do any additional setup after loading the view.
}
-(void)myTheme{
    NSString * file = [MySettingOptions defaultOptions].backColor;
    if(self.view.frame.size.width == 375){
        NSString * back = [NSString stringWithFormat:@"%@6",file];
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:back]];
    }else{
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:file]];
    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

}
-(NSMutableArray *)totalArray{
    if (_totalArray) {
        return _totalArray;
    }
    _totalArray = [[NSMutableArray alloc]init];
    return _totalArray;
}
-(NSMutableArray *)likeArray{
    if (_likeArray) {
        return _likeArray;
    }
    _likeArray = [[NSMutableArray alloc] init];
    return _likeArray;
}
-(void)getDataWithUrlStr:(NSString *)urlStr{
    self.allClassModelArray = [[NSMutableArray alloc]init];
    NSURL * fileUrl = [[NSBundle mainBundle]URLForResource:@"LabelList" withExtension:nil];
    NSData * data = [NSData dataWithContentsOfURL:fileUrl];
    NSMutableDictionary * sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSDictionary * dic = sourceDic[@"result"];
    self.totalArray = [NSMutableArray arrayWithArray:dic[@"titles"]];

    for (NSDictionary * oneItem in dic[@"hot"]) {
        ClassLabelModel * classModel = [[ClassLabelModel alloc]init];
        [classModel setValuesForKeysWithDictionary:oneItem];
        [self.allClassModelArray addObject:classModel];
    }
    for (NSDictionary * oneItem in dic[@"list"]) {
        ClassLabelModel * classModel = [[ClassLabelModel alloc]init];
        [classModel setValuesForKeysWithDictionary:oneItem];
        [self.allClassModelArray addObject:classModel];
    }
    MySettingOptions * option = [MySettingOptions defaultOptions];
//    NSLog(@"%@",option.mutableLabels);
    for (ClassLabelModel * classModel in self.allClassModelArray) {
        if ([option.mutableLabels containsObject:classModel.label_content]) {
            [self.sourceArray addObject:classModel];
            [self.likeArray addObject:classModel.label_content];
        }
    }
//    self.firstTableVC.sourceArray = [NSMutableArray array];
//    for (int i = 0; i<self.sourceArray.count/2; i++) {
//        [self.firstTableVC.sourceArray addObject:self.sourceArray[i]];
//    }
//    self.secondTableVC.sourceArray = [NSMutableArray array];
//    for (int i = (int)self.sourceArray.count/2; i<self.sourceArray.count; i++) {
//        [self.secondTableVC.sourceArray addObject:self.sourceArray[i]];
//    }
    
}
//-(void)didClickSettingBarButton:(UIBarButtonItem *)barButton{
//    
//}
-(void)didClickFenleiBarButton:(UIBarButtonItem *)barButton{
    static BOOL flag = YES;
    if (flag) {
        classView = [[ClassSettingView alloc]init];
        [classView.doneButton addTarget:self action:@selector(didClickFenleiBarButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.tabBarController.view addSubview:classView];
        [self.totalArray removeObjectsInArray:self.likeArray];

        classView.userLikeArray = self.likeArray;
        classView.otherArray = self.totalArray;
        
//        classView.otherArray = self.
        [classView animationToShow];
    }else{
        [classView removeFromSuperview];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];        
        [self.sourceArray removeAllObjects];
        for (ClassLabelModel * clModel in self.allClassModelArray) {
            if ([self.likeArray containsObject:clModel.label_content]) {
                [self.sourceArray addObject:clModel];
            }
        }
        
        [qtmquitView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }
    

    flag = !flag;
    
}
#pragma mark -get懒加载
//-(UITableViewController *)firstTableVC{
//    if (_firstTableVC == nil) {
//        self.firstTableVC = [[MYTableViewController alloc]initWithStyle:UITableViewStylePlain];
//        self.firstTableVC.tableScrollDelegate = self;
//        [self addChildViewController:self.firstTableVC];
//        self.firstTableVC.tableView.frame = CGRectMake(0, 64, self.view.frame.size.width/2.0, self.view.frame.size.height-113);
//        [self.view addSubview:self.firstTableVC.tableView];
//    }
//    return _firstTableVC;
//}
//-(UITableViewController *)secondTableVC{
//    if (_secondTableVC == nil) {
//        self.secondTableVC = [[MYTableViewController alloc]initWithStyle:UITableViewStylePlain];
//        self.secondTableVC.tableScrollDelegate = self;
//        [self addChildViewController:self.secondTableVC];
//        self.secondTableVC.tableView.frame = CGRectMake(self.view.frame.size.width/2.0, 64, self.view.frame.size.width/2.0, self.view.frame.size.height-113);
//        [self.view addSubview:self.secondTableVC.tableView];
//
//    }
//    return _secondTableVC;
//}
-(NSMutableArray *)sourceArray{
    if (_sourceArray==nil) {
        self.sourceArray = [[NSMutableArray alloc]init];
    }
    return _sourceArray;
}

//-(void)tableViewScrollWithContentOffset:(CGPoint)contentOffset AndViewController:(MYTableViewController *)viewController{
//    if (viewController ==self.firstTableVC) {
//        [self.secondTableVC.tableView setContentOffset:contentOffset];
//    }else{
//        [self.firstTableVC.tableView setContentOffset:contentOffset];
//    }
//}

#pragma mark
- (NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView{
    return self.sourceArray.count;
}
- (TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath {
    TMPhotoQuiltViewCell *cell = (TMPhotoQuiltViewCell *)[quiltView dequeueReusableCellWithReuseIdentifier:@"PhotoCell"];
    if (!cell) {
        cell = [[TMPhotoQuiltViewCell alloc] initWithReuseIdentifier:@"PhotoCell"];
    }
    ClassLabelModel * classModel = self.sourceArray[indexPath.row];
    NSURL * imageUrl = [NSURL URLWithString:classModel.image_src];
    [cell.photoView sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    cell.titleLabel.text = classModel.label_content;
    return cell;
}

#pragma mark - TMQuiltViewDelegate

- (NSInteger)quiltViewNumberOfColumns:(TMQuiltView *)quiltView {
    
    
    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft
        || [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)
    {
        return 3;
    } else {
        return 2;
    }
}

- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath
{
    ClassLabelModel * classModel = self.sourceArray[indexPath.row];
    CGFloat height = classModel.image_h * self.view.bounds.size.width * 0.5 / classModel.image_w;
    if (height > 60) {
        return height;
    }
    return 80;
}

- (void)quiltView:(TMQuiltView *)quiltView didSelectCellAtIndexPath:(NSIndexPath *)indexPath
{

    ClassLabelModel * classModel = self.sourceArray[indexPath.row];
    NSString * str = [classModel.label_content URLEncodedString];
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 27)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIBarButtonItem appearance].tintColor;
    titleLabel.text = classModel.label_content;
    titleLabel.font = [UIFont systemFontOfSize:[MySettingOptions defaultOptions].titleFontValue];
    
    
    if ([classModel.label_content isEqualToString:@"本周最热"]) {
        NSString * theStr = @"http://gif.duowan.com/index.php?r=gif/hotList&page=1&pageSize=30";
        GifController * gifVC = [[GifController alloc]initWithStyle:UITableViewStylePlain Url:theStr];
        gifVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:gifVC animated:YES];
        gifVC.navigationItem.titleView = titleLabel;
        UIBarButtonItem * leftBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_nav"] style:UIBarButtonItemStylePlain target:gifVC.navigationController action:@selector(popViewControllerAnimated:)];
        
        gifVC.navigationItem.leftBarButtonItem = leftBarButton;
        gifVC.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>) gifVC;

        return;
    }
    NSString * theStr = @"http://gif.duowan.com/index.php?r=gif/labelDetailList&page=1&pageSize=30&label=%E7%A5%9E%E5%A5%87%E6%9C%BA%E6%A2%B0";
    NSRange range = [theStr rangeOfString:@"&label="];
    NSString * replaceStr = [theStr substringFromIndex:range.location];
    NSLog(@"%@",replaceStr);
    NSString * urlStr = [theStr stringByReplacingOccurrencesOfString:replaceStr withString:[NSString stringWithFormat:@"&label=%@",str]];
    
    GifController * gifVC = [[GifController alloc]initWithStyle:UITableViewStylePlain Url:urlStr];
    gifVC.navigationItem.titleView = titleLabel;
    gifVC.hidesBottomBarWhenPushed = YES;
    UIBarButtonItem * leftBarButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_nav"] style:UIBarButtonItemStylePlain target:gifVC.navigationController action:@selector(popViewControllerAnimated:)];

    gifVC.navigationItem.leftBarButtonItem = leftBarButton;
    gifVC.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>) gifVC;
    [self.navigationController pushViewController:gifVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
